package com.cicadalane.androlate;

/*
 * Copyright (C) 2011 cicada.software@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import java.io.File;
import java.io.FilenameFilter;
import java.util.Collection;
import java.util.Vector;

/*
 * File find implementation
 */
public class FileFind {
	public static File[] find(File directory, FilenameFilter filter,
			boolean recurse) {
		Collection<File> files = FileFind.ls(directory.getAbsoluteFile(),
				filter, recurse);
		File[] result = new File[files.size()];
		files.toArray(result);
		return result;
	}

	private static Collection<File> ls(File directory, FilenameFilter filter,
			boolean recurse) {
		Vector<File> result = new Vector<File>();
		File[] entries = directory.listFiles();
		if (entries == null || entries.length <= 0)
			return result;

		for (File entry : entries) {
			if (filter == null || filter.accept(directory, entry.getName())) {
				result.add(entry);
			}
			if (recurse && entry.isDirectory()) {
				result.addAll(ls(entry, filter, recurse));
			}
		}
		return result;
	}
}
